import { useEffect } from 'react'

import { createOrgApi, queryOrgTreeApi, updateOrgApi } from '@/api/sys/organization'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { requestWithTry } from '@/utils/request'

const EditDeptModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { departmentId } = row

  useEffect(() => {
    if (!departmentId) return
    form.setFieldsValue({
      ...row,
    })
  }, [departmentId])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      exclude: departmentId,
      field: 'parentDepartmentId',
      label: '上级部门',
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryOrgTreeApi,
          fieldNames: {
            value: 'departmentId',
            label: 'departmentName',
          },
        },
      },
    },
    {
      field: 'departmentName',
      label: '部门名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Input',
        props: {
          maxLength: 20,
          placeholder: '10个字以内',
        },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      departmentId,
      ...values,
    }
    await requestWithTry(departmentId ? updateOrgApi : createOrgApi, params)
  }
  return (
    <AekModal title={departmentId ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditDeptModal.PromiseThen = PromiseThen

export default EditDeptModal
